/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.txweb.bundle.provider;

import com.jspx.utils.*;
import com.jspx.txweb.bundle.table.BundleTable;
import com.jspx.txweb.bundle.BundleProvider;
import com.jspx.io.WriteFile;
import com.jspx.io.AbstractWrite;

import java.util.*;
import java.io.*;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.SAXException;
import org.xml.sax.Attributes;

/**
 * Created by IntelliJ IDEA.
 * User:chenYuan (mail:39793751@qq.com)
 * Date: 2005-6-24
 * Time: 15:37:33
 */
public class XMLBundleProvider extends BundleProvider// implements Bundle, Serializable
{
    private static final Logger log = LoggerFactory.getLogger(XMLBundleProvider.class);
    //  private String exname = ".properties.xml";
    private File file = null;

    //表示路径
    public XMLBundleProvider() {

    }

    private File getFile() {
        if (file != null) return file;
        String name = namespace + "_" + dataType + ".properties.xml";
        URL url = ClassUtil.getResource(name);
        if (url == null) {
            url = ClassUtil.getResource("/" + name);
        }
        if (url != null) {
            file = new File(url.getPath());
        }
        file = new File(name);
        return file;
    }

    public boolean save(String key, String value) throws Exception
    {
        return save( key,  value,0);
    }



    /**
     * 保存
     *
     * @param bundletable
     * @return boolean
     */
    public boolean save(BundleTable bundletable) {
        if (bundletable == null) return false;
        cache.put(bundletable.getIdx(), bundletable.getContext());
        try {
            AbstractWrite aw = new WriteFile();
            aw.setFile(file.getAbsolutePath());
            aw.setEncode(encode);
            aw.setContent(toXML(), false);
        } catch (Exception e) {
            log.error(bundletable.getContext(), e);
        }
        return true;
    }


    /**
     * 得到绑定方式的列表
     *
     * @return List<BundleTable>
     */
    public List<BundleTable> getList() {
        List<BundleTable> list = new ArrayList<BundleTable>();
        for (String key : cache.keySet()) {
            if (StringUtil.isNULL(key)) continue;
            list.add(getBundleTable(key));
        }
        return list;
    }


    public String getValue(String key) {
        for (Object o : getList()) {
            BundleTable bundleTable = (BundleTable) o;
            if (bundleTable.getIdx().equals(key)) return bundleTable.getContext();
        }
        return StringUtil.empty;
    }



    public BundleTable getBundleTable(final String keys)
    {
        if (StringUtil.isNULL(keys)) return null;
        BundleTable bundleTable = new BundleTable();
        bundleTable.setIdx(keys);
        bundleTable.setDataType(dataType);
        bundleTable.setNamespace(namespace);
        return bundleTable;
    }

    //boolean createForXML(String xmlString);
    //彻底删除数据
    public boolean deleteAll()
    {
        File file = getFile();
        if (file.isFile() && file.exists() && file.delete())
        {
            try
            {
                return file.createNewFile();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return false;

    }

    //载入数据
    public void loadMap()
    {
        File file = getFile();
        if (file.isFile() && file.exists())
        {
            try
            {
                ReadXMLProperties rxp = (ReadXMLProperties) XMLUtil.parseXmlFile(new ReadXMLProperties(), file);
                cache.putAll(rxp.getMap());
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }


     class ReadXMLProperties extends DefaultHandler
    {
        private CharArrayWriter contents = new CharArrayWriter();
        private Map<String, String> map = new HashMap<String, String>();
        private String key = StringUtil.empty;

        public ReadXMLProperties()
        {
        }

        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException
        {
            contents.reset();
            if ("value".equalsIgnoreCase(localName))
            {
                key = attributes.getValue("key");
            }
        }

        public void endElement(String namespaceURI,
                               String localName,
                               String qName) throws SAXException
        {
            if ("value".equalsIgnoreCase(localName))
            {
                map.put(key, contents.toString());
            }
        }

        public void characters(char[] ch, int start, int length)
                throws SAXException
        {

            contents.write(ch, start, length);
        }

        public Map<String, String> getMap()
        {
            return map;
        }
    }

      public boolean remove(String key) {
         cache.remove(key);
         return true;
      }


    public  void flush() throws Exception
    {
        cache.clear();
    }

}